package com.cqrcb.cloud.config.redis.constant;

import com.cqrcb.cloud.config.redis.template.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * redis 工具常量
 *
 * @author yangxueyong
 * @date 2018/5/21 11:59
 */
@Slf4j
@Component
public class RedisTools {

    @Autowired(required = false)
    private RedisRepository redisRepository;

    /**
     * Redis 是否可用
     */
    private boolean REDIS_AVAILABLE = true;

    /**
     * 0 未变化
     * 1 从true变为false
     * 2 从false变为true
     */
    private int REDIS_AVAILABLE_CHANGE = 0;

    public boolean getRedisAvailable(){
        if(!REDIS_AVAILABLE){
            getAndSetRedisAvailable();
        }
        return REDIS_AVAILABLE;
    }

    private ThreadPoolExecutor quotaAyncPoolExecutor = new ThreadPoolExecutor(2, 2, 2, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(3),
            new ThreadPoolExecutor.DiscardPolicy());


    public boolean getAndSetRedisAvailable(boolean flag){
        REDIS_AVAILABLE = false;
        return getAndSetRedisAvailable();
    }

    public boolean getAndSetRedisAvailable(){
        quotaAyncPoolExecutor.execute(()->{
            try {
                redisRepository.flushDB();
                REDIS_AVAILABLE = true;
                //false变为true
                REDIS_AVAILABLE_CHANGE = 2;
            }catch (Exception e){
                log.error("存入测试key失败,e->{}", e.getMessage());
                REDIS_AVAILABLE = false;
                //从true变为false
                REDIS_AVAILABLE_CHANGE = 1;
            }
        });
        return REDIS_AVAILABLE;
    }
}
